#include "stdafx.h"
#include "ViewGDI.h"

const COLORREF kBackground = RGB( 255 , 255 , 255 );

ViewGDI::ViewGDI( Model * const inModel , HWND hWnd ) :
	View( inModel ) , mhWnd( hWnd )
{
	// Prepare double buffer
	RECT rect;
	GetClientRect(hWnd,&rect);
	
	int width	= rect.right - rect.left;
	int height	= rect.bottom + rect.left;

	HDC hdc;
	HDC hdcMem;
	HBITMAP bitmap;

	hdc = GetDC( hWnd );
	hdcMem = CreateCompatibleDC(hdc);
	bitmap = CreateCompatibleBitmap(hdc, width, height);
	SelectObject( hdcMem , bitmap);
	ReleaseDC( hWnd , hdc );

	this->mhMemDC		= hdcMem;
	this->mBackBuffer	= bitmap;

	this->mfWidth	= float( width );
	this->mfHeight	= float( height );
}

ViewGDI::~ViewGDI(void)
{
	if( this->mhMemDC )
	{
		DeleteDC( this->mhMemDC );
		this->mhMemDC = NULL;
	}
	if( this->mBackBuffer )
	{
		DeleteObject( this->mBackBuffer );
		this->mBackBuffer = NULL;
	}
}

void ViewGDI::Render()
{
	HWND hWnd = this->getHWND();
	// PAINTSTRUCT ps;
	// HDC hdc = BeginPaint(hWnd, &ps);
	HDC hdc = GetDC( hWnd );

	RECT rect;

	GetClientRect(hWnd,&rect);

	int width	= rect.right - rect.left;
	int height	= rect.bottom + rect.left;

	HBRUSH hBrushBG = CreateSolidBrush( kBackground );
	FillRect( this->mhMemDC , &rect , hBrushBG );

	// Transparent text... for now
	::SetBkMode( this->mhMemDC , TRANSPARENT );

	// Draw objects.
	this->OnRender();

	// Show FPS
	float fps = this->doFPSCheck();
	TCHAR str[ 256 ];
	swprintf( str , 256 , _T( "%.0f FPS" ) , fps ); 
	this->SetTxtColor( RGB( 0 , 0 , 255 ) );
	this->TxtOut( 0 , 0 , str );

	BitBlt(hdc, 0, 0, width , height , this->mhMemDC, 0, 0, SRCCOPY);

	DeleteObject( hBrushBG );

	ReleaseDC( hWnd , hdc );
	// EndPaint(hWnd, &ps);

	ValidateRect( hWnd , NULL );
}

void ViewGDI::OnRender()
{
}

void ViewGDI::SetTxtColor( COLORREF color )
{
	::SetTextColor( this->mhMemDC , color );
}

void ViewGDI::SetBkMode( int inMode )
{
	::SetBkMode( this->mhMemDC , inMode );
}

void ViewGDI::SetBkColor( COLORREF color ) 
{
	::SetBkColor( this->mhMemDC , color );
}

void ViewGDI::TxtOut( float fX , float fY , const TCHAR * pStr )
{
	::TextOut( this->mhMemDC , int( fX ) , int( fY ) , pStr , wcslen( pStr ) );
}

void ViewGDI::DrawTxt( float x1 , float y1 , float x2 , float y2 , const TCHAR * pStr )
{
	RECT rect;
	
	rect.left	= int( x1 );
	rect.top	= int( y1 );
	rect.right	= int( x2 );
	rect.bottom	= int( y2 );

	::DrawText( this->mhMemDC , pStr , wcslen( pStr ) , &rect , DT_CENTER | DT_VCENTER | DT_SINGLELINE );
}

void ViewGDI::DrawRct( float x1 , float y1 , float x2 , float y2 , COLORREF color )
{
	RECT rect;
	
	rect.left	= int( x1 );
	rect.top	= int( y1 );
	rect.right	= int( x2 );
	rect.bottom	= int( y2 );

	HBRUSH hBrushBG = CreateSolidBrush( kBackground );

	FillRect( this->mhMemDC , &rect , hBrushBG );

	DeleteObject( hBrushBG );
}

